"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Search, Upload, FolderPlus, Moon, Sun } from "lucide-react"
import { UploadDialog } from "@/components/upload-dialog"
import { CreateFolderDialog } from "@/components/create-folder-dialog"
import { useTheme } from "next-themes"

interface TopBarProps {
  searchQuery: string
  onSearchChange: (query: string) => void
  onRefreshRequest?: () => void
  currentFolderId?: number
}

export function TopBar({ searchQuery, onSearchChange, onRefreshRequest, currentFolderId = 0 }: TopBarProps) {
  const [showUpload, setShowUpload] = useState(false)
  const [showCreateFolder, setShowCreateFolder] = useState(false)
  const { theme, setTheme } = useTheme()
  const [isComposing, setIsComposing] = useState(false)
  const [localValue, setLocalValue] = useState(searchQuery)

  // 同步外部 searchQuery 的变化到本地状态
  useEffect(() => {
    setLocalValue(searchQuery)
  }, [searchQuery])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    // 始终更新本地显示值
    setLocalValue(value)
    // 如果不在选词过程中，立即触发搜索
    if (!isComposing) {
      onSearchChange(value)
    }
  }

  const handleCompositionStart = () => {
    setIsComposing(true)
  }

  const handleCompositionEnd = (e: React.CompositionEvent<HTMLInputElement>) => {
    setIsComposing(false)
    // 选词完成后触发搜索
    const value = (e.target as HTMLInputElement).value
    setLocalValue(value)
    onSearchChange(value)
  }

  return (
    <>
      <header className="h-16 border-b border-border bg-card px-6 flex items-center justify-between gap-4">
        <div className="flex-1 max-w-2xl">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              type="search"
              placeholder="搜索文件名或内容..."
              className="pl-10"
              value={localValue}
              onChange={handleInputChange}
              onCompositionStart={handleCompositionStart}
              onCompositionEnd={handleCompositionEnd}
            />
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" size="icon" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
            <Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
            <Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
          </Button>
          <Button variant="outline" className="gap-2 bg-transparent" onClick={() => setShowCreateFolder(true)}>
            <FolderPlus className="h-4 w-4" />
            新建文件夹
          </Button>
          <Button className="gap-2" onClick={() => setShowUpload(true)}>
            <Upload className="h-4 w-4" />
            上传文件
          </Button>
        </div>
      </header>

      <UploadDialog
        open={showUpload}
        onOpenChange={setShowUpload}
        onUploadSuccess={onRefreshRequest}
        parentFolderId={currentFolderId}
      />
      <CreateFolderDialog
        open={showCreateFolder}
        onOpenChange={setShowCreateFolder}
        onCreateSuccess={onRefreshRequest}
        parentId={currentFolderId}
      />
    </>
  )
}
